/**
 * Added by zhangyanhu C01012,2014-11-18
 */
package com.vxfly.helioscamera.Tool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.LinkedList;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Video;
import android.text.TextUtils;
import android.util.Log;

import com.vxfly.helioscamera.global.App.GlobalInfo;
import com.vxfly.helioscamera.log.WriteLogToDevice;

/**
 * Added by zhangyanhu C01012,2014-11-18
 */
public class FileTools {
//private LinkedList<File> list;
//private LinkedList<String> fileList;
	private  static String[] Urls = null;
	private  static Bitmap bitmap = null;  
	private  static Bitmap newBitmap = null; 
	public static String[] getUrls(String path){
			String filePath = Environment.getExternalStorageDirectory().toString() + path;
			File folder = new File(filePath);
			WriteLogToDevice.writeLog("[Test] -- getUrls" ,"path="+filePath);
			String[] temp = folder.list();
			WriteLogToDevice.writeLog("[Test] -- getUrls", "temp=" +temp);
			WriteLogToDevice.writeLog("[Test] -- getUrls", "temp size="+ temp.length);
			LinkedList<String> tempList = new LinkedList<String>();
			tempList.clear();
			for (int ii = 0; ii < temp.length; ii++) {
				if(temp[ii].endsWith(".jpg") || temp[ii].endsWith(".png") || temp[ii].endsWith(".PNG") || temp[ii].endsWith(".JPG")){
					tempList.addLast(temp[ii]);
				}
			}
		Collections.sort(tempList,String.CASE_INSENSITIVE_ORDER);
		tempList = sortForFile(tempList);
			Urls = new String[tempList.size()];
			for (int ii = 0; ii < tempList.size(); ii++) {
				Urls[ii] = Environment.getExternalStorageDirectory().toString()
						+ path + tempList.get(ii);
			}
			tempList = null;
			temp = null;
			Log.d("1111", "Urls.length ==" + Urls.length);
		return Urls;
	}
	
	public static String[] getLocalVideoUrls(String path){
		File folder = new File(Environment.getExternalStorageDirectory().toString() + path);
		String[] temp = folder.list();
		LinkedList<String> tempList = new LinkedList<String>();
		tempList.clear();
		for (int ii = 0; ii < temp.length; ii++) {
			if(temp[ii].endsWith(".MP4") || temp[ii].endsWith(".wmv") || temp[ii].endsWith(".mp4") || temp[ii].endsWith(".3gp")
					|| temp[ii].endsWith(".MOV") ||temp[ii].endsWith(".mov")||temp[ii].endsWith(".AVI")||temp[ii].endsWith(".avi")){
				tempList.addLast(temp[ii]);
			}
		}
		Urls = new String[tempList.size()];
		for (int ii = 0; ii < tempList.size(); ii++) {
			Urls[ii] = Environment.getExternalStorageDirectory().toString() + path + tempList.get(ii);
		}
		tempList = null;
		temp = null;
		Log.d("1111", "Urls.length ==" + Urls.length);
		return Urls;
	}
	private static void getAllFiles(File root){  
        
	        File files[] = root.listFiles();  
	        LinkedList<File> list =new LinkedList<File>();  
	        if(files != null)  
	        for(File f:files){  
	          
	            if(f.isDirectory()){  
	                getAllFiles(f);  
	            }  
	            else{  
	                list.addLast(f);  
	            }  
	        }  
		} 
		
	public static void GetFiles(String Path) //搜索目录，扩展名，是否进入子文件夹
	{
		Path = Environment.getExternalStorageDirectory().toString() + Path;
		Log.e("tigertiger","path ="+Path);
		//JpgFileFilter jpgFileFilter = new JpgFileFilter();
	    String[] files = new File(Path).list();
	    Log.e("tigertiger","f.getName() ="+files[0]);
	}
	
	public static Bitmap getBitmapFromFolder(String path,int reqWidth){
		WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "getBitmapFromFolder path ="+path);
		path = Environment.getExternalStorageDirectory().toString() + path;
		Log.e("tigertiger","path ="+path);
		//JpgFileFilter jpgFileFilter = new JpgFileFilter();
		File temp = new File(path);
		if (!temp.exists()) {
			temp.mkdirs();
		}
		String[] files = temp.list();
		
		if (files == null || files.length == 0) {
			Log.e("tigertiger", "files == null || files.length  == 0");
			WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "no files found");
			return null;
		}
		
		LinkedList<String> tempList = new LinkedList<String>();
		tempList.clear();
		for (int ii = 0; ii < files.length; ii++) {
			//tempList.addLast(files[ii]);
			if (files[ii].endsWith(".jpg") || files[ii].endsWith(".png") || files[ii].endsWith(".PNG") || files[ii].endsWith(".JPG")) {
				tempList.addLast(files[ii]);
			}
		}				
		if(tempList.size() <= 0){
			Log.e("3333", "tempList.size()="+tempList.size());
			return null;
		}
		Collections.sort(tempList,String.CASE_INSENSITIVE_ORDER);
		tempList = sortForFile(tempList);
		path = path + tempList.get(0);
	    WriteLogToDevice.writeLog("[Normal] -- FileTools: ","get first file name ="+path);
	    //return getImageThumbnail(context, resolver, path) ;
	    return getBitmapByWidth(path,reqWidth,5);
	//
	}
	
	
	 public static Bitmap getBitmapByWidth(String localImagePath, int width,int addedScaling){
	        if (TextUtils.isEmpty(localImagePath))
	        {
	            return null;
	        }
	        
	        Bitmap temBitmap = null;
	        
	        try
	        {
	            BitmapFactory.Options outOptions = new BitmapFactory.Options();
	            
	            // 设置该属性为true，不加载图片到内存，只返回图片的宽高到options中。
	            outOptions.inJustDecodeBounds = true;
	            
	            // 加载获取图片的宽高
	            BitmapFactory.decodeFile(localImagePath, outOptions);
	            
	            int height = outOptions.outHeight;
	            
	            if (outOptions.outWidth > width)
	            {
	                // 根据宽设置缩放比例
	                outOptions.inSampleSize = outOptions.outWidth / width + 1
	                        + addedScaling;
	                outOptions.outWidth = width;
	                
	                // 计算缩放后的高度
	                height = outOptions.outHeight / outOptions.inSampleSize;
	                outOptions.outHeight = height;
	            }
	            
	            // 重新设置该属性为false，加载图片返回
	            outOptions.inJustDecodeBounds = false;
	            outOptions.inPurgeable = true;
	            outOptions.inInputShareable = true;
	            temBitmap = BitmapFactory.decodeFile(localImagePath, outOptions);
	        }
	        catch (Throwable t)
	        {
	            t.printStackTrace();
	        }
	        
	        return temBitmap;
	    }
	 
	 public static Bitmap getVideoBitmapFromFolder(String path,Context context){
		 	ContentResolver resolver = GlobalInfo.getInstance().getCurrentApp().getContentResolver();
		 	//Context context2 =  GlobalInfo.getInstance().getCurrentApp().getApplicationContext();
		 	WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "getVideoBitmapFromFolder path ="+path);
		 	String videoPath = Environment.getExternalStorageDirectory().toString() + path;
		 	File folder = new File(videoPath);
			if (!folder.exists()) {
				folder.mkdirs();
			}
			String[] temp = folder.list();
			if (temp == null || temp.length == 0) {
				Log.e("tigertiger", "files == null || files.length  == 0");
				WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "no files found");
				return null;
			}
			LinkedList<String> tempList = new LinkedList<String>();
			tempList.clear();
			for (int ii = 0; ii < temp.length; ii++) {
				if(temp[ii].endsWith(".MP4") || temp[ii].endsWith(".mp4") || temp[ii].endsWith(".MOV") ||temp[ii].endsWith(".mov")
						|| temp[ii].endsWith(".wmv")  || temp[ii].endsWith(".3gp")||temp[ii].endsWith(".AVI")||temp[ii].endsWith(".avi")){
					tempList.addLast(temp[ii]);
				}
			}
			if(tempList.size() <= 0){
				WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "tempList.size()="+tempList.size());
				Log.e("3333", "tempList.size()="+tempList.size());
				return null;
			}
			videoPath = videoPath + tempList.getFirst();
			
			WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "videoPath="+ videoPath);
			newBitmap =  getVideoThumbnail(context,resolver ,videoPath);
			//newBitmap = getVideoThumbnail(videoPath);
			//bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);
			WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "bitmap="+bitmap);
			return newBitmap;
			//return getVideoThumbnailFromFolder(Urls[0],reqWidth,reqWidth,MediaStore.Images.Thumbnails.MICRO_KIND);
			
	 }
	 
	 public static String getNewestVideoFromDirectory(String directoryPath){
		 
		 WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "getNewestVideoFromDirectory directoryPath ="+directoryPath);
		 	String videoPath = Environment.getExternalStorageDirectory().toString() + directoryPath;
		 	File folder = new File(videoPath);
			if (!folder.exists()) {
				folder.mkdirs();
			}
			String[] temp = folder.list();
			if (temp == null || temp.length == 0) {
				Log.e("tigertiger", "files == null || files.length  == 0");
				WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "no files found");
				return null;
			}
			LinkedList<String> tempList = new LinkedList<String>();
			tempList.clear();
			for (int ii = 0; ii < temp.length; ii++) {
				if(temp[ii].endsWith(".MP4") || temp[ii].endsWith(".mp4") || temp[ii].endsWith(".MOV") ||temp[ii].endsWith(".mov")
						|| temp[ii].endsWith(".wmv")  || temp[ii].endsWith(".3gp")||temp[ii].endsWith(".AVI")||temp[ii].endsWith(".avi")){
					tempList.addLast(temp[ii]);
				}
			}
			if(tempList.size() <= 0){
				WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "tempList.size()="+tempList.size());
				Log.e("3333", "tempList.size()="+tempList.size());
				return null;
			}
			videoPath = videoPath + tempList.getFirst();
			
			return videoPath;
	 }
	 public static void copyFile(int resourceId) {
		 	File Folder = new File("/sdcard/SportCamResoure/");	        
	        if (!Folder.exists())
	        {
	        	Folder.mkdir();
	        }
	    	String filename = Environment.getExternalStorageDirectory().toString() + "/SportCamResoure/";
	    	Log.d("1111", "copyFile filename ==" + filename);
		// String filename =
		// Environment.getExternalStorageDirectory().toString() + "/Pictures/";
		InputStream in = null;
		OutputStream out = null;
		File outFile = null;
		String fileName1 = "sphost.BRN";
		File file = new File(filename, fileName1);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			in = GlobalInfo.getInstance().getCurrentApp().getResources().openRawResource(resourceId);

			outFile = new File(filename + fileName1);
			Log.d("1111", "output file" + outFile.getAbsolutePath());
			out = new FileOutputStream(outFile);
			byte[] buffer = new byte[1024];
			int read;
			while ((read = in.read(buffer)) != -1) {
				out.write(buffer, 0, read);
			}
		} catch (IOException e) {
			Log.e("1111", "Failed to copy file", e);
		} finally {
			try {
				in.close();
				out.flush();
				out.close();
				in = null;
				out = null;
			} catch (Exception e) {
			}
		}
	}

	public static boolean isFileExists(String fileName) {
		String filename = Environment.getExternalStorageDirectory().toString() + "/SportCamResoure/";
		File file = new File(filename, fileName);
		return file.exists();

	}

	public static long getFileSize(File f) {
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getFileSize(flist[i]);
			} else {
				size = size + flist[i].length();
			}
		}
		return size;
	}
	
	public static LinkedList<String> sortForFile(LinkedList<String> fileList)
	{
		LinkedList<String> nameList = new LinkedList<String>();
		nameList.clear();
		int length = fileList.size();
		int ii;
		for(ii = 0;ii < length;ii++)
		{
			nameList.addLast(fileList.get(length- 1 -ii)); 
		}
		
		return nameList;
		
		
	}
	
	private static Bitmap getVideoThumbnailFromFolder(String videoPath, int width, int height,  
            int kind) {  
        Bitmap bitmap;  
        // 获取视频的缩略图  
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);  
        Log.d("5555","bitmap = "+ bitmap);

        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,  ThumbnailUtils.OPTIONS_RECYCLE_INPUT);  
        Log.d("5555","bitmap2 = "+ bitmap);
        return bitmap;  
    }
	
	
	 
	 public static Bitmap getVideoThumbnail(Context context, ContentResolver cr, String Videopath) {  
		 WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "start getVideoThumbnail_2  videoPath="+ Videopath);
         ContentResolver testcr = context.getContentResolver();  
         String[] projection = { MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID, };  
         String whereClause = MediaStore.Video.Media.DATA + " = '" + Videopath + "'";  
         Cursor cursor = testcr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, whereClause,  
                         null, null);  
         int _id = 0;  
         String videoPath = "";  
         if (cursor == null || cursor.getCount() == 0) {  
        	 WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "start getVideoThumbnail_2  cursor="+ cursor);
                 return null;  
         }  
         if (cursor.moveToFirst()) {  

                 int _idColumn = cursor.getColumnIndex(MediaStore.Video.Media._ID);  
                 int _dataColumn = cursor.getColumnIndex(MediaStore.Video.Media.DATA);  
                 do {  
                         _id = cursor.getInt(_idColumn);  
                         videoPath = cursor.getString(_dataColumn);  
                 } while (cursor.moveToNext());  
         }  
         WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "getVideoThumbnail_2  _id="+ _id);
         cursor.close(); 
         BitmapFactory.Options options = new BitmapFactory.Options();  
         options.inDither = false;  
         options.inPreferredConfig = Bitmap.Config.RGB_565;  
         //Bitmap bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr, _id, Images.Thumbnails.MINI_KIND,options);
         Bitmap bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr, _id, Video.Thumbnails.MINI_KIND,options);
//         for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
//        	cursor.getLong(cursor.getColumnIndex("_ID"));       
//         	bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr,_id,Video.Thumbnails.MICRO_KIND,null);
//         } 
         WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "end getVideoThumbnail_2  bitmap="+ bitmap);
         return bitmap;  
	 }
	 
	  public static Bitmap getImageThumbnail(Context context, ContentResolver cr, String Imagepath) {
		  WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "start getImageThumbnail  Imagepath="+ Imagepath);
          ContentResolver testcr = context.getContentResolver();
          String[] projection = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, };
          String whereClause = MediaStore.Images.Media.DATA + " = '" + Imagepath + "'";
          Cursor cursor = testcr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, whereClause,
                          null, null);
          int _id = 0;
          String imagePath = "";
          if (cursor == null || cursor.getCount() == 0) {
                  return null;
          }
          if (cursor.moveToFirst()) {
                  int _idColumn = cursor.getColumnIndex(MediaStore.Images.Media._ID);
                  int _dataColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
                  do {
                          _id = cursor.getInt(_idColumn);
                          imagePath = cursor.getString(_dataColumn);
                  } while (cursor.moveToNext());
          }
          WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "getImageThumbnail  _id="+ _id);
          cursor.close();
          BitmapFactory.Options options = new BitmapFactory.Options();
          options.inDither = false;
          options.inPreferredConfig = Bitmap.Config.RGB_565;
          Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(testcr, _id, Images.Thumbnails.MINI_KIND,
                          options);
          WriteLogToDevice.writeLog("[Normal] -- FileTools: ", "end getImageThumbnail  bitmap="+ bitmap);
          return bitmap;
  }
	
	
}
